import { HttpCode } from '#/utils/contacts.js';
import { TjContent, TjModal, TjModalTitle } from '@/tjComponents';
import { ExclamationCircleOutlined, PlusCircleOutlined, SaveOutlined } from '@ant-design/icons';
import { Button, message, Modal } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import TjTable from '../../../components/TjTable';
import { nxQueryList, addNxList } from '../../service';
import NxModalContent from '../NxModalContent';
import { checkMonth, columns } from './helper';
import './index.less';

const { confirm } = Modal;

interface INxConfigProps {
  marketId?: string;
  marketName?: string;
  canImport?: boolean;
  filterValues?: any;
  changeGlobalLoading?: (loading: boolean) => void;
}

const NxConfig: React.FC<INxConfigProps> = (props) => {
  const { canImport } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [req, setReq] = useState<any>();

  const changeLoading = (status: boolean) => {
    setLoading(status);
    props.changeGlobalLoading && props.changeGlobalLoading(status);
  };

  const add = () => {
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      content: <NxModalContent />,
      destroyOnClose: true,
      maskClosable: false,
      onOk: (value) => {
        const newDataSource = [...dataSource];
        newDataSource.push({
          ...value,
          id: moment().valueOf(),
          marketId: props.marketId,
          marketName: props.marketName,
          month: _.sortBy(value.month),
          year: moment(req.year).format('YYYY'),
        });
        setDataSource(newDataSource);
      },
    });
  };

  const del = (index: number) => {
    confirm({
      title: '确定要删除该条数据吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const newDataSource = [...dataSource];
        newDataSource.splice(index, 1);
        setDataSource(newDataSource);
      },
    });
  };

  const edit = (row: any, index: number) => {
    const values = {
      ...row,
    };
    TjModal.open({
      title: <TjModalTitle title="编辑" />,
      content: <NxModalContent values={values} />,
      destroyOnClose: true,
      maskClosable: false,
      onOk: (value) => {
        const newDataSource = [...dataSource];
        newDataSource[index] = {
          ...value,
          marketId: props.marketId,
          marketName: props.marketName,
          month: _.sortBy(value.month),
        };
        setDataSource(newDataSource);
      },
    });
  };

  const save = () => {
    if (dataSource.length <= 0) {
      return message.error('数据不能为空');
    }
    const allMonth = [];
    for (let i = 0; i < dataSource.length; i++) {
      allMonth.push(...dataSource[i].month);
    }
    const { missing } = checkMonth(_.uniq(allMonth));
    if (missing.length > 0) {
      const missingArr: string[] = [];
      missing.forEach((v: number) => {
        missingArr.push(`${v}月`);
      });
      return message.error(`缺少${missingArr.join(',')}的数据`);
    }
    changeLoading(true);

    const { year } = req;
    const newDataSource = dataSource.map((v) => {
      if (!v.year) {
        v.year = moment(year).format('YYYY');
      }
      return v;
    });

    addNxList({ list: newDataSource })
      .then((res) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          message.success('当前年份数据保存成功');
          query(req);
        } else {
          message.error(`保存失败：${res.message}`);
        }
      })
      .finally(() => {
        changeLoading(false);
      });
  };

  const query = (parmas: any) => {
    const { year } = parmas;
    changeLoading(true);
    nxQueryList({ year: moment(year).format('YYYY'), marketId: props.marketId })
      .then((res) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          setDataSource(res.data);
        }
      })
      .finally(() => {
        changeLoading(false);
      });
  };

  useEffect(() => {
    if (props.filterValues) {
      setReq(props.filterValues);
      query(props.filterValues);
    }
  }, [props.filterValues]);

  return (
    <TjContent
      titleLeft="宁夏时段"
      className="nx-config"
      titleRight={
        <div className="opts">
          <Button type="link" icon={<PlusCircleOutlined />} loading={loading} onClick={add}>
            新增
          </Button>
          <Button type="primary" icon={<SaveOutlined />} onClick={save} loading={loading}>
            保存
          </Button>
        </div>
      }
    >
      <TjTable
        columns={columns({ del, edit })}
        dataSource={dataSource}
        isLoading={loading}
        primaryKey="id"
      />
    </TjContent>
  );
};

export default NxConfig;
